// routes.js
import React from 'react';
import { Navigate } from 'react-router-dom';
import BasicLayout from '@/components/BasicLayout';
import Loading from '@/components/Loading';
import { lazy, Suspense } from 'react';
import Home from '@/pages/Home';

// 懒加载
import PropTypes from 'prop-types';
import DoctorService from '../pages/DoctorService';
import DoctorGroup from '../pages/DoctorGroup';
import DigitalMarketing from '../pages/DigitalMarketing';
import About from '../pages/About';


const routes = [
  { path: '', element: <Navigate to="/web/index" replace={true} /> }, // Redirect 重定向
  {
    path: '/login',
    element: React.lazy(() => import('@/pages/Login')),
  },
  {
    path: '/',
    element: <BasicLayout />,
    children: [
      {
        path: '/web/index', 
        element: <Home />,
        checkAuthority: false,
      },
      {
        path: '/web/doctor-service',
        name: '医生服务',
        // element: React.lazy(() => import('@/pages/DoctorService')),
        element: <DoctorService />,
        checkAuthority: false,
      },
      {
        path: '/web/doctor-group',
        name: '医生集团',
        // element: React.lazy(() => import('@/pages/DoctorGroup')),
        element: <DoctorGroup />,
        checkAuthority: false,
      },
      {
        path: '/web/digital-marketing',
        name: '数字化营销',
        // element: React.lazy(() => import('@/pages/DigitalMarketing')),
        element: <DigitalMarketing />,
        checkAuthority: false,
      },
      {
        path: '/web/about',
        name: '关于良医健康',
        // element: React.lazy(() => import('@/pages/About')),
        // element: <Suspense fallback={<div>路由加载中。。。</div>}>
        //  {React.lazy(() => import('../pages/About'))}
        // </Suspense>,
        async lazy() {
            let { About } = await import("../pages/About");
            return { Component: About };
          },
        //   lazy: () => import("../pages/About"),
        element: <About />,
        checkAuthority: false,
      },
    ],
  },
];

function LazyElement(props) {
    const { importFunc } = props;
    const LazyComponent = lazy(importFunc);
    return (
        <Suspense fallback={<Loading />}>
            <LazyComponent />
        </Suspense>
    );
}

LazyElement.propTypes = {
    importFunc: PropTypes.func.isRequired,
};
  
  // 处理routes 如果element是懒加载，要包裹Suspense
  function dealRoutes(routesArr) {
    if (routesArr && Array.isArray(routesArr) && routesArr.length > 0) {
      routesArr.forEach((route) => {
        if (route.element && typeof route.element == 'function') {
          const importFunc = route.element
          route.element = <LazyElement importFunc={importFunc} />
        }
        if (route.children) {
          dealRoutes(route.children)
        }
      })
    }
  }
  dealRoutes(routes)

export default routes;
